package com.shell.governor.user.rx;

import com.shell.bee.base.utils.Encryptor;
import com.shell.bee.base.utils.RandomUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.bee.base.utils.SystemUtil.SystemMode;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.governor.modules.message.keyword.SmsAutPwdKeyword;
import com.shell.governor.modules.util.MessageSender;
import com.shell.governor.organization.dao.PubOrganDao;
import com.shell.governor.user.UserEvent;
import com.shell.governor.user.dao.PubUserDao;
import com.shell.governor.user.po.PubUser;
import com.shell.governor.user.po.PubUserOpt;
import com.shell.properties.GovernorProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SetUserPasswordSubscriber extends OnErrorNotImplementedSubscriber<UserEvent> {
	@Autowired
	GovernorProperties governorProperties;
	@Autowired
	PubOrganDao organDao;
	@Autowired
	PubUserDao pubUserDao;

	public void onApplicationEvent(UserEvent event) {
		PubUser user = event.getUser();
		PubUserOpt opt = event.getUserOpt();
		if ((event.isNeedApprover()) && (event.getUserOpt().getBizCode().equals("0"))) {
			return;
		}
		if (StringUtil.notEmpty(user.getUserId())) {
			PubUser oldUser = (PubUser) this.pubUserDao.selectByPrimaryKey(user.getUserId());
			if (StringUtil.notEmpty(oldUser.getPassword())) {
				return;
			}
		}
		String password = "";
		if (!SystemUtil.SystemMode.prod.equals(SystemUtil.getSystemMode())) {
			password = this.governorProperties.getUserDefaultPassword();
		} else {
			password = String.valueOf(RandomUtil.getRandomInt(8));
		}
		user.setPassword(Encryptor.encryptWithMD5(password));
		this.pubUserDao.updateByPrimaryKey(user);

		PubUser admin = (PubUser) this.pubUserDao.selectByPrimaryKey(user.getCreatorId());

		SmsAutPwdKeyword smsAutPwdKeyword = new SmsAutPwdKeyword();
		smsAutPwdKeyword.setUrl(this.governorProperties.getUrl());
		smsAutPwdKeyword.setLoginName(user.getLoginName());
		smsAutPwdKeyword.setCusName(admin.getUserName());
		smsAutPwdKeyword.setPassWord(password);

		MessageSender.sendMessageToPhone(user.getPhoneNo(), CommonDataUtil.getUserId(), "MT02106", smsAutPwdKeyword);
	}
}
